package com.qinsoft.frame.common;

import java.util.Date;
import java.util.List;

import org.directwebremoting.WebContextFactory;

import com.qinsoft.business.module.bean.Module;
import com.qinsoft.business.module.dao.ModuleDao;
import com.qinsoft.business.permit.bean.Permit;
import com.qinsoft.business.permit.dao.PermitDao;
import com.qinsoft.business.user.bean.User;
import com.qinsoft.business.user.dao.UserDao;
import com.qinsoft.frame.messages.WriteMessage;

public class AppUtil
{
    
    public static UserInfo select()
    {
        String sessionId = WebContextFactory.get().getSession().getId();
        return UserUtil.getInstance().getUserInfo(sessionId);
    }
    
    public static UserInfo select(UserInfo userInfo)
    {
        try
        {
            //查询模块
            List<Module> module = ModuleDao.select();
            //查询权限
            List<Permit> list = PermitDao.select(userInfo.getNick());
            int m = 0;
            for(Permit permit : list)
            {
                m |= Integer.parseInt(permit.getItemPermit(),2);
            }
            //修改权限
            String limits = Integer.toBinaryString(m);
            if(limits.length()<module.size())
            {
                int size = limits.length();
                for(int i=0;i<module.size()-size;i++)
                {
                    limits = "0"+limits;
                }
            }
            char[] charArray = limits.toCharArray();
            for(int i=0; i<charArray.length; i++)
            {
                module.get(i).setFlag(charArray[i]=='1');
            }
            Date date = list.get(list.size()-1).getDeadline();
            long between = (date.getTime()-new Date().getTime())/1000/(24*3600);
            //设置等级名称
            userInfo.setLevel(list.get(list.size()-1).getPermitName());
            //设置模块
            userInfo.setModule(module);
            //设置到期时间
            userInfo.setDeadline(between);
            User user = new User(userInfo, limits, date);
            UserDao.keep(user);
        }
        catch (Exception e)
        {
            WriteMessage.WriteErrorLog("com.qinsoft.frame.common.select("+ userInfo.getNick() +")", e);
        }
        return userInfo;
    }
}